package com.jhj.provider.user.controller;

import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jhj.provider.user.po.b.model.UserSmsToken;
import com.jhj.provider.user.service.UserSmsTokenService;
import com.jhj.provider.user.utils.Constants;
import com.jhj.utils.AppResultData;
import com.jhj.utils.SmsUtil;
import com.jhj.utils.TimeStampUtil;

@RestController
public class UserSmsTokenController {

	@Autowired
	private UserSmsTokenService userSmsTokenService;

	@Value("${spring.profiles.active}")
	private String applicationActive;

	/**
	 * 获取验证码
	 * 
	 * @param mobile
	 *            手机号
	 * @param sms_type
	 *            验证码类型：0=验证码，1=支付
	 * 
	 */
	@RequestMapping(value = "/api/user/getCode.json", method = RequestMethod.GET)
	public AppResultData<Object> getCode(@RequestParam("mobile") String mobile,
			@RequestParam(value = "sms_type", defaultValue = "0") Integer smsType) {

		AppResultData<Object> data = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		String code = RandomStringUtils.randomNumeric(4);
		HashMap<String, String> sendSms = new HashMap<String, String>();
		if (!applicationActive.equals("dev")) {
			String[] content = new String[] { code, Constants.GET_CODE_MAX_VALID };
			sendSms = SmsUtil.SendSms(mobile, Constants.GET_USER_VERIFY_ID, content);
		} else {
            code = "000000";
			sendSms.put("statusCode", Constants.SMS_SUCCESS_CODE);
			sendSms.put("msg", "");
		}

		UserSmsToken userSmsToken = new UserSmsToken();
		userSmsToken.setMobile(mobile);
		userSmsToken.setUserId(0);
		userSmsToken.setSmsType(smsType);
		userSmsToken.setSmsToken(code);
		userSmsToken.setIsSuceess((sendSms.get(Constants.SMS_SUCCESS_CODE) != null
				&& sendSms.get(Constants.SMS_SUCCESS_CODE).equals(Constants.SMS_SUCCESS_CODE)) ? Constants.SMS_SUCCESS
						: Constants.SMS_FAIL);
		userSmsToken.setSmsReturn(sendSms.get(Constants.SMS_STATUS_CODE));
		userSmsToken.setAddTime(TimeStampUtil.getNowSecond().intValue());
		userSmsToken.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
		userSmsTokenService.insert(userSmsToken);

		return data;

	}

	/**
	 * 获取验证码
	 * 
	 * @param mobile
	 *            手机号
	 * @param smsToken
	 * @param sms_type
	 *            验证码类型：0=验证码，1=支付
	 * return data
	 */
	@RequestMapping(value = "/api/user/checkCode.json", method = RequestMethod.GET)
	public AppResultData<Object> checkCode(
			@RequestParam("mobile") String mobile,
			@RequestParam("smsToken") String smsToken,
			@RequestParam(value = "smsType",required = false,  defaultValue = "0") Integer smsType) {

		AppResultData<Object> data = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		
		UserSmsToken searchVo = new UserSmsToken();
		searchVo.setMobile(mobile);
		searchVo.setSmsType(smsType);

		List<UserSmsToken> list = userSmsTokenService.selectBySearchVo(searchVo, "add_time desc");

		if (list.isEmpty())  {
			data.setStatus(Constants.ERROR_999);
			data.setMsg("验证码不正确");
			return data;
		} else {
			UserSmsToken userSmsToken = list.get(0);
			if (!smsToken.equals(userSmsToken.getSmsToken())) {
				data.setStatus(Constants.ERROR_999);
				data.setMsg("验证码不正确");
				return data;
			} else {
				long expTime = TimeStampUtil.compareTimeStr(userSmsToken.getAddTime().longValue(), System.currentTimeMillis() / 1000);
				// 如果验证码超时，返回超时错误
				if (expTime > 1800) {
					data.setStatus(Constants.ERROR_999);
					data.setMsg("验证码已失效");
					return data;
				}
			}
		}

		return data;

	}

	/**
	 * 查询用户最后一条验证码
	 * @param mobile
	 * @param user_type
	 * 
	 * @return smsToken
	 */
	@RequestMapping(value = "/api/user/selectCode.json", method = RequestMethod.GET)
	public AppResultData<Object> getCode(
			@RequestParam("mobile") String mobile,
			@RequestParam(value = "user_type", required = false, defaultValue = "0") int userType) {

		AppResultData<Object> data = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		UserSmsToken smsToken = userSmsTokenService.selectByMobileAndType(mobile, userType);
		if (smsToken == null) {
			data.setMsg("验证码异常");
			data.setStatus(Constants.ERROR_999);
			return data;
		}

		data.setData(smsToken);
		return data;
	}

}
